<?php

namespace App\Console\Commands;

use App\Http\Controllers\Resource\ZyController;
use App\Models\ResourceBusinessName;
use App\Models\ResourceTypeExternal;
use App\Models\ResourceZy;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 * 掌阅科技
 */
class ZyMysqlData extends Command
{

    // 使用 命令行执行  php artisan command:ZyMysqlData
    // 若使用 linux 后台执行则使用  nohup php artisan command:ZyMysqlData &   //输入完后，关闭命令行
    // 或者使用 crontab 定时执行此命令行

    //  protected $type_data_total = 200000; //每个类型数据总量
    protected $limit = 50; //每页限制条数
    protected $up_start_page = 1; //开始页，默认为 1
    protected $resource_business_id = 8; //资源商id

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:ZyMysqlData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步掌阅科技数据到数据库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $resourceBusinessNameModel = new  ResourceBusinessName();
        $resource_business_name_info = $resourceBusinessNameModel->where('id', $this->resource_business_id)->where('is_del', 1)->first();
        if (empty($resource_business_name_info)) {
            Log::channel('zycmdlog')->debug('资源商不存在或已被删除');
            die;
        }
        try {
            //先同步类型
            $obj = new ZyController();
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $resourceModel = new ResourceZy();
            $data = $obj->getBookIdAll();
            if (empty($data)) {
                Log::channel('zycmdlog')->debug('获取所有资源ID不存在');
                die;
            }

            $ebook_data = $resourceModel->getDataIntersection(1, $data[1]);
            $audio_book_data = $resourceModel->getDataIntersection(2, $data[2]);
            //删除指定数据
            if (!empty($ebook_data['del'])) {
                $resourceModel->deleteData(1, $ebook_data['del']);
            }
            //删除指定数据
            if (!empty($audio_book_data['del'])) {
                $resourceModel->deleteData(2, $audio_book_data['del']);
            }

            Log::channel('zycmdlog')->debug('本次同步电子书上架数量: ' . count($ebook_data['add']));
            Log::channel('zycmdlog')->debug('本次同步有声书上架数量: ' . count($audio_book_data['add']));
            Log::channel('zycmdlog')->debug('本次同步电子书下架数量: ' . count($ebook_data['del']));
            Log::channel('zycmdlog')->debug('本次同步有声书下架数量: ' . count($audio_book_data['del']));

            //添加电子书数据
            $book_ids = [];
            $start_key = 0;
            sort($ebook_data['add']); //重置key
            foreach ($ebook_data['add'] as $key => $val) {
                //一次性加载100条数据
                if (count($book_ids) >= 99 || count($audio_book_data['add']) == $key + 1) {
                    $book_ids[] = $val; //需要把当期那数据追加进去
                    $end_key = $key;

                    $datail_data = $obj->getBookDetail($book_ids, 1);
                    $result_id = '';
                    foreach ($datail_data as $detail) {
                        $type_info['name'] = !empty($detail['lastCate']) ? $detail['lastCate'] : (!empty($detail['secondCate']) ? $detail['secondCate'] : $detail['firstCate']); //取一级分类
                        $type_info['resource_business_id'] = $this->resource_business_id;
                        $type_info['big_type_id'] = 1; //4 为期刊 1为电子书
                        $type_info['level'] = 1; //1 级大类
                        $type_id = $resourceTypeExternalModel->getTypeNameNoAdd($type_info);
                        $detail['type_id'] = $type_id;
                        $detail['big_type_id'] = 1;
                        $result = $resourceModel->addData($detail);
                        $result_id .= $result . '、';
                    }
                    trim($result_id, '、');
                    Log::channel('zycmdlog')->debug('掌阅数据 key: ' . $start_key . '~' . $end_key . ' 同步完成: ' . $result_id);
                    $start_key = $key + 1;
                    $book_ids = [];
                } else {
                    $book_ids[] = $val;
                }
            }
            Log::channel('zycmdlog')->debug('全量同步电子书上架数据处理完毕');

            //添加电子书数据
            $book_ids = [];
            $start_key = 0;
            sort($audio_book_data['add']); //重置key
            foreach ($audio_book_data['add'] as $key => $val) {
                if (count($book_ids) > 100 || count($audio_book_data['add']) == $key + 1) {
                    $book_ids[] = $val; //需要把当期那数据追加进去
                    $end_key = $key;

                    $datail_data = $obj->getBookDetail($book_ids, 2);
                    $result_id = '';
                    foreach ($datail_data as $detail) {
                        $type_info['name'] = $type_info['firstCate']; //取一级分类
                        $type_info['resource_business_id'] = $this->resource_business_id;
                        $type_info['big_type_id'] = 1; //4 为期刊 1为电子书
                        $type_info['level'] = 1; //1 级大类
                        $type_id = $resourceTypeExternalModel->getTypeNameNoAdd($type_info);
                        $detail['type_id'] = $type_id;
                        $detail['big_type_id'] = 1;
                        $result = $resourceModel->addData($detail);
                        $result_id .= $result . '、';
                    }
                    trim($result_id, '、');
                    Log::channel('zycmdlog')->debug('掌阅数据 key: ' . $start_key . '~' . $end_key . ' 同步完成: ' . $result_id);
                    $start_key = $key + 1;
                    $book_ids = [];
                } else {
                    $book_ids[] = $val;
                }
            }
            Log::channel('zycmdlog')->debug('全量同步有声书上架数据处理完毕');


            Log::channel('zycmdlog')->debug('数据全部同步完成');
            // echo '数据全部同步完成';
            //更新同步时间
            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['last_synch_time' => date('Y-m-d H:i:s')]);
        } catch (\Exception $e) {
            Log::channel('zycmdlog')->debug('数据处理出现异常:' . $e->getMessage() . ';File:' . $e->getFile() . ';Line:' . $e->getLine() . ';');
        }
    }
}
